﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.ComponentModel;
using System.Text.RegularExpressions;

namespace TA.DotNetUtils
{
	[TypeConverter(typeof(IntRangeConverter))]
	[Serializable]
	public struct IntRange
	{
		public IntRange(int start, int end)
			: this()
		{
			this._start = start;
			this._end = end;
		}

		public int Start { get { return this._start; } set { this._start = value; } }
		public int End { get { return this._end; } set { this._end = value; } }

		public override string ToString()
		{
			return string.Format("{0} - {1}", this._start, this._end);
		}

		int _start, _end;
	}
	public class IntRangeConverter : TypeConverter
	{
		static readonly Regex rgx = new Regex(@"^\s*(?<Start>\d+)\s*[\-–—]\s*(?<End>\d+)\s*$");
		public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
		{
			if (sourceType.Equals(typeof(string)))
				return true;
			return base.CanConvertFrom(context, sourceType);
		}
		public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
		{
			if (value is string)
			{
				Match m = rgx.Match((string)value);
				IntRange r = new IntRange();
				if (m.Groups["Start"].Success)
					r.Start = int.Parse(m.Groups["Start"].Value);
				if (m.Groups["End"].Success)
					r.End = int.Parse(m.Groups["End"].Value);

				return r;
			}
			return base.ConvertFrom(context, culture, value);
		}
	}
}